package booklib.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.swing.JOptionPane;

import booklib.model.User;

/**
 * 用户dao类
 * @author yaer
 *
 */
public class UserDao {
	/**
	 * 登录验证
	 * @param con
	 * @param user
	 * @return
	 * @throws Exception
	 */
	public User login(Connection con,User user)throws Exception{
		User resultUser=null;
		String sql="select * from t_user where userName=? and password=?";
		PreparedStatement pstmt=con.prepareStatement(sql);
		pstmt.setString(1,user.getUserName());
		pstmt.setString(2, user.getPassword());
		ResultSet rs=pstmt.executeQuery();
		if(rs.next()){
			resultUser=new User();
			resultUser.setId(rs.getInt("id"));
			resultUser.setUserName(rs.getString("userName"));
			resultUser.setPassword(rs.getString("password"));
		}
		return resultUser;		
	}
	/**
	 * 注册验证
	 * @param con
	 * @param user
	 * @return
	 * @throws Exception
	 */
	public int Register(Connection con,User user)throws Exception{
		User resultUser=null;
		String sql="select * from t_user where userName=? and password=?";
		PreparedStatement pstmt=con.prepareStatement(sql);
		pstmt.setString(1,user.getUserName());
		pstmt.setString(2, user.getPassword());
		ResultSet rs=pstmt.executeQuery();
		int id=0;
		if(rs.next()){
			resultUser=new User();
			resultUser.setId(rs.getInt("id"));
			resultUser.setUserName(rs.getString("userName"));
			resultUser.setPassword(rs.getString("password"));
			
		}
		String sql2="select * from t_user";
		PreparedStatement pstmt2=con.prepareStatement(sql2);
		ResultSet rs1=pstmt2.executeQuery();
		while(rs1.next()) { id++; } 
		
		if(resultUser==null){
			String sql1="insert into t_user values(?,?,?)";
			PreparedStatement pstmt1= con.prepareStatement(sql1);
			
			pstmt1.setInt(1, id);
			pstmt1.setString(2, user.getUserName());
			pstmt1.setString(3, user.getPassword());
			return pstmt1.executeUpdate();
		}
		else{
			return -1;
			
		}
				
	}
}
